package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constans.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.search.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService  {

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private KafkaTemplate<String,String > kafkaTemplate;

    /**
     * 生成静态文件上传到minIO中
     *
     * @param apArticle
     * @param content
     */
    @Override
    @Async//表示执行的异步方法
    public void buildArticleToMinIO(ApArticle apArticle, String content) {

        try {
        //1.获取文章内容，根据文章id去查询
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(
                Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId())
        );
        //2.获取模板
        Template template = configuration.getTemplate("article.ftl");
            //封装数据模型
            Map params=new HashMap<>();
            params.put("content", JSONArray.parseArray(content));

            //声明空的字符串写入流
            StringWriter stringWriter=new StringWriter();
            //3.生成静态html文件
            template.process(params,stringWriter);//相当于stringwriter流中就应该有了数据流

            //4.上传到minio中
            InputStream inputStream=new ByteArrayInputStream(stringWriter.toString().getBytes());
            String path = fileStorageService.uploadHtmlFile("", apArticleContent.getArticleId() + ".html", inputStream);
            //5.修改ap_article表中的static_url字段值
            apArticle = apArticleMapper.selectById(apArticleContent.getArticleId());
            if(apArticle!=null){
                apArticle.setStaticUrl(path);
                apArticleMapper.updateById(apArticle);
            }

            //发送消息
            SearchArticleVo vo=new SearchArticleVo();
            BeanUtils.copyProperties(apArticle,vo);
            vo.setLayout(Integer.valueOf(apArticle.getLayout()));
            vo.setContent(content);
            vo.setStaticUrl(path);
            kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(vo));


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
